package com.qf.event.listener;

/*
 *  @author Administrator
 *  @version V1.0
 *  @Project smartdeviceplatgorm
 *  @Package com.qf.event.listener
 *  @Description
 *  @Date2022/3/24 0024 20:21
 */

import com.qf.bean.SysDevice;
import com.qf.event.DevicePowerEvent;
import com.qf.service.SysDeviceService;
import com.qf.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DevicePowerListener {
    private SysDeviceService sysDeviceService;

    @Autowired
    public void setSysDeviceService(SysDeviceService sysDeviceService) {
        this.sysDeviceService = sysDeviceService;
    }

    @EventListener
    @Async
    public void onEvent(DevicePowerEvent event) {
        String deviceId=event.getDeviceId();
        String ip = event.getIp();
        String locationByIp = RequestUtil.getLocationByIp(ip);//获取到地区
        SysDevice device = new SysDevice();
        device.setDeviceId(deviceId);
        System.err.println("event.getDeviceStaus:"+event.getDeviceStaus().toString());
        switch (event.getDeviceStaus()) {
            case ONLINE:
                device.setConnectTime(new Date());
                device.setCurrentConnectIp(event.getIp());
                device.setConnectLocation(locationByIp);
                device.setIsOnline(1);
                break;
            case OFFLINE:
                device.setLostConnectTime(new Date());
                device.setIsOnline(2);
                break;
        }
        sysDeviceService.updateDeviceById(device);
    }
}
